const db = require('db');

module.exports = async ctx => {
    const { connection, run } = db.init();
    try {
        const id = ctx.params.id;
        ctx.status = 200;
        ctx.body = {
            list: await queryEntry(id, run),
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = error;
    }
    connection.end();
}

async function queryEntry(id, run) {
    const sqlStr = `
    SELECT o.* , c.clientName
    FROM settlementEntry as s
    LEFT JOIN orders AS o ON s.ordersId = o.id 
    LEFT JOIN client AS c ON o.clientId = c.id 
    WHERE s.settlementId = ${id}
    `

    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return result.rows;
}